// The Swift Programming Language
// https://docs.swift.org/swift-book

import AppDecoder
import Alamofire
import Foundation

public struct AppNetwork {
    
    public static func sayHellow(_ string: String) {
        print("你好啊====>\(string)")
    }
    
    public static func myDecoder<T>(_ type: T.Type, param: [String:Any]) -> T? where T: Decodable {
        if let model = LsqDecoder.decode(type, param: param) {
            print("我解析出来了啊===>\(model)")
            return model
        }
        return nil
    }
    
    public static func alamofireAct() async {
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 20
        let sharedManager = Alamofire.Session(configuration: configuration)
        
        let url = "https://apiswise.123cx.com/ope/weather"
        let param = ["areaName":"长沙市"]
        let task = sharedManager.request(url, method: .get, parameters: param, encoding: URLEncoding.default, headers: [:])
        
        let response = await task.redirect(using: .follow).serializingData().response
        switch response.result {
        case .success(let data):
            let json = self.getJsonString(with: data)
            print("这个接口是啥啊==>\(json ?? "没有东西啊啊")")
            break
        case .failure(let error):
            print("接口调用失败==>\(error)")
            break
        }
    }

    private static func getJsonString(with data: Data?) -> String? {
        guard let d = data else {
            return nil
        }
        let encoder = JSONEncoder()
        encoder.outputFormatting = .prettyPrinted
//        guard let data = try? encoder.encode(data) else {
//            return nil
//        }
        guard let jsonStr = String(data: d, encoding: .utf8) else {
            return nil
        }
        return jsonStr
    }
}
